package initialize

import (
	"fmt"
	"log"
	"os"
	"reward-server/global"
	"time"

	mq "reward-server/models/mysql"

	"go.uber.org/zap"
	"gorm.io/driver/mysql"
	"gorm.io/gorm"
	"gorm.io/gorm/logger"
	"gorm.io/gorm/schema"
)

// 初始化MySQL数据库
func InitMySQL() *gorm.DB {

	// 参考 https://github.com/go-sql-driver/mysql#dsn-data-source-name 获取详情
	config := global.ServerConfig.MySQL
	dsn := fmt.Sprintf("%s:%s@tcp(%s:%s)/%s?charset=utf8mb4&parseTime=True&loc=Local",
		config.User, config.Password, config.Host, config.Port, config.DbName)
	newLogger := logger.New(
		log.New(os.Stdout, "", log.LstdFlags), // io writer
		logger.Config{
			SlowThreshold: time.Second, // 慢 SQL 阈值
			LogLevel:      logger.Info, // Log level
			Colorful:      true,        // 彩色打印
		},
	)
	// 全局模式
	var err error
	db, err := gorm.Open(mysql.Open(dsn), &gorm.Config{
		//设置表结构命名取出 后面生成的s
		NamingStrategy: schema.NamingStrategy{
			SingularTable: true,
			TablePrefix:   "", //不设前缀

		},
		Logger:                                   newLogger,
		DisableForeignKeyConstraintWhenMigrating: true,
	})
	if err != nil {
		zap.S().Errorf("连接数据库失败%s", err)
	}
	return db
}

// 根据struct 生成 mysql 表
func RegisterTables(db *gorm.DB) {

	err := db.Set("gorm:table_options", "ENGINE=InnoDB").AutoMigrate(

		&mq.WishingWall{},
	)
	if err != nil {
		zap.S().Errorf("注册数据表结构出错:%v ", err)
	} else {
		zap.S().Info("数据表结构同步完成")
	}
}
